package com.futao.springbootlearn20220224.value;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * mysteel-bone动态更新value值的方案
 *
 * @author futao@gmail.com
 * @date 2022/4/18
 */
@RestController
@RequestMapping("/dynamic-value")
public class DynamicValue {

    static final Map<String, Field> filedValueNameFieldMap = new HashMap<>();

    static {
        Field[] declaredFields = DynamicValue.class.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            Value valueAnn = declaredField.getAnnotation(Value.class);
            if (valueAnn != null) {
                String fieldAnnValue = valueAnn.value().replace("${", "").replace("}", "");
                filedValueNameFieldMap.put(fieldAnnValue, declaredField);
            }
        }
    }

    @Value("${app.username}")
    private String username;

    @GetMapping
    public String getValue() {
        return username;
    }

    @PostMapping
    public boolean setValue(@RequestParam("valueName") String valueName, @RequestParam("valueValue") String valueValue) throws IllegalAccessException {
        Field field = filedValueNameFieldMap.get(valueName);
        if (field != null) {
            field.setAccessible(true);
            field.set(this, valueValue);
            return true;
        }
        return false;
    }
}
